<?php
class sort extends Admin {

    private $sort_list = null;
    private $name = "分类";

    function __construct() {
        parent::__construct();
        $this->sort_list = $this->sort();
        $this->model->table = 'sort';
    }

    public function index( $c, $a ) {
        include $this->display( $c );
    }

    public function add( $c, $a ) {
        include $this->display( $c );
    }

    public function edit( $c, $a ) {
        if ( !$id = intval( R( "id" ) ) ) {
            $this->error();
        }
        if ( !$result = $this->sort_list[ $id ] ) {
            $this->error();
        }
        include $this->display( $c );
    }

    public function save() {
        foreach ( $_POST as $key => $val ) {
            if ( $key == 'alias' ) $val = str_replace( " ", "-", strtolower( $val ) );
            $rows[ $key ] = htmlspecialchars( trim( $val ) );
        }
        if ( isset ( $rows[ 'id' ] ) && intval( $rows[ 'id' ] ) ) {
            $id = $rows[ 'id' ];
            unset( $rows[ 'id' ] );
            $this->model->update( array( 'id' => $id ), $rows );
        } else {
            $this->model->create( $rows );
        }

        $this->model->Cache()->update( 'sort' );
        $this->success( '保存分类成功!' );
    }

    public function del() {
        if ( !$id = intval( R( "id" ) ) ) {
            $this->error();
        }
        if ( $this->model->find( array( 'sid' => $id ) ) ) {
            $this->error( '该分类下还有子分类,请先删除子分类!' );
        }

        // 删除分类
        $this->model->delete( array( 'id' => $id ) );

        // 删除分类下文章
        $this->model->table = 'article';
        $this->model->delete( array( "sid" => $id ) );

        // 更新分类缓存
        $this->model->Cache()->update( 'sort' );

        $this->success( '删除分类成功!' );
    }

    /*
     * 分类排序
     */
    public function oid() {
        foreach ( $_POST[ 'oid' ] as $k => $v ) {
            $this->model->update( array( 'id' => $k ), array( 'oid' => $v ) );
        }

        // 更新分类缓存
        $this->model->Cache()->update( 'sort' );

        $this->success( '更新分类排序成功!' );
    }
}